<?php
namespace api\modules\v1\controllers;

use common\bonus\BaseBonus;
use common\bonus\StaticRelease;
use common\models\Balance;
use common\models\BalanceLog;
use common\models\StaticInstance;
use common\models\TradeClub;
use common\models\TradeCommodity;
use common\models\TradeOrder;

class TradeClubController extends CoreController
{

    public function actionInfo(){

        $params = array(
            'field'	=> ['*'],
            'order' => 'create_time desc',
            'page'	=> $this->request('page','1'),
            'limit' => $this->request('page_size',10),
            'memberId'=>$this->_memberId,
        );

        $list =TradeClub::dataList([],$params,['api']);
        $pages = TradeClub::$pages;

        $instance = StaticInstance::getAll(['member_id'=>$this->_memberId,'status'=>1,'order_type'=>'4'],'commodity_id,type,in_num,was_num');
        /*获取俱乐部合同本金*/
        $instance = round(array_sum(array_column($instance,'in_num')),2)??0;

        /*开始时间*/
        $startTime = strtotime(date('Y-m-d 00:00:00',time()));
        /*今日合约收益*/
        $day_instance = BalanceLog::getAll("source_type in (19) and log_type=1 and create_time>='".$startTime."' and create_time<='".time()."' and member_id=$this->_memberId",'balance');
        $day_num = round(array_sum(array_column($day_instance,'balance')),2)??0;
        $num = BalanceLog::find()->where("source_type in (19) and log_type=1 and member_id=$this->_memberId")->sum('balance');
        $this->out('列表',$list,array('pages'=>$pages,'instance'=>$instance,'day_num'=>$day_num,'num'=>round($num,2)));
    }

    /*参加签约*/
    public function actionSetCommodity(){
        $arr['member_id']    = $this->_memberId;
        $arr['goods_id']     = $this->request('commodity_id');


        if (!$arr['goods_id'])
            $this->error('请选择投资项目');

        if ($this->_member['paypwd'] !== md5($this->request('password')))
            $this->error('密码有误');


        $where = 'commodity_id='.$arr['goods_id'].' and sell_end_time >="'.date('Y-m-d',time())
            .'" and sell_start_time<="'.date('Y-m-d',time()).'"';

        $data  = TradeClub::getOne($where);
        if (!$data) $this->error('项目不存在');

        $userBalance = Balance::getOne('member_id='.$arr['member_id'].' and balance_type=1','balance');
        if (!$userBalance)  $this->error('用户余额为空');
        $arr['amount']=$data['money'];
        if ($userBalance['balance']<$data['money']) $this->error('用户余额不足');
        $arr['type']  = 4;

        $tradeOrder = new TradeOrder();
        try {

            //创建订单
            $transaction = \Yii::$app->db->beginTransaction();
            $orderId     =  $tradeOrder->addData($arr,$this->_member);
            if(!$orderId) throw new \Exception("订单创建失败");

            //扣除余额账本
            $res = Balance::reduceBalance($arr['member_id'],1,$data['money'],18,$orderId);
            if (isset($res['state']) && $res['state']==false) throw new \Exception($res['msg']);

            //增加合同钱包
            $re = Balance::addBalance($arr['member_id'],3,$data['money'],18,$orderId);
            if (isset($re['state']) && $re['state']==false) throw new \Exception($re['msg']);
            $transaction->commit();

            //触发后续
            $params              = array();
            $params['money']     = $data['money'];
            $params['member_id'] = $this->_memberId;
            $params['source_id'] = 1;
            $params['mch_id']    = 0;
            $params['desc']         = 'from 【'.$this->_member['member_name'].'】';
            $params['order_type']   =4;
            $params['period']       = $data['period']??0;
            $params['day_income']   = $data['day_income'];
            $params['commodity_id'] = $arr['goods_id'];

            StaticRelease::bonusAction($params);
            $this->out('签约成功');
        }catch (\Exception $e){
            $transaction->rollback();
            $this->error($e->getMessage());
        }
    }

    /*我的俱乐部合同列表*/
    public function actionCommodityList(){
        $whereArr['where']['order_type']=4;
        $whereArr['where']['member_id']=$this->_memberId;

        $params = array(
            'field'	=> ['id','in_num','type','status','bonus_day','period_day','order_type','create_time','commodity_id'],
            'order' => 'create_time desc',
            'page'	=> $this->request('page',1),
            'limit' => $this->request('page_size',10),
            'member_id'=>$this->_memberId,
        );

        $data  = StaticInstance::dataList($whereArr,$params,['winning']);
        $count = StaticInstance::$pages;
        $this->out('合约列表',$data,['count'=>$count]);
    }

}